<?php

namespace App\Models;

class Brand extends BaseModel
{
    protected $table = "brand";

    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 按条件查询单条数据
     */
    public function getOne(array $where, $fields = '*')
    {
        return $this->multiSelect($fields)->multiWhere($where)->first();
    }

    /**
     * 按条件查询全部数据,根据配置显示条数显示
     */
    public function getList(array $where = [], $fields = '*', $order = '', $pageSize = '')
    {
        if ($pageSize) {
            return $this->multiSelect($fields)->multiWhere($where)->multiOrder($order)->paginate($pageSize);
        } else {
            return $this->multiSelect($fields)->multiWhere($where)->multiOrder($order)->get();
        }
    }

    /**
     * 根据条件删除数据
     */
    public function del(array $where)
    {
        return $this->multiWhere($where)->delete();
    }

    /**
     *插入数据
     */
    public function add($data)
    {
//        dd($data);
        return $this->insertGetId($data);
    }

    /**
     *更新数据
     */
    public function up($where, $data)
    {
        return $this->multiWhere($where)->update($data);
    }

    /**
     * 获取和
     */
    public function getSum($where, $field)
    {
        return $this->multiWhere($where)->sum($field);
    }

    /**
     * 字段递加
     */
    public function inc($where, $field, $n)
    {
        return $this->multiWhere($where)->increment($field, $n);
    }

    /**
     * @param $request
     * @return mixed
     * 根据id获取品牌信息
     */
    public function getBrandInfo($request)
    {
        $where['id'] = $request['id'];
        $res = $this->getOne($where);
        if ($res) {
            $res = $res->toArray();
        }
        return $res;
    }

    public function getBrandAgentList($request)
    {
        $agent = new Agent();
        $where['bid'] = ['like', '%,' . $request['id'] . ',%'];
        //dd($where['bid']);
        //$where['bid'] = $request['id'];
        if ($request['lev']) {
            $where['lev'] = $request['lev'];
        }
        if ($request['provice_id']) {
            $where['provice_id'] = $request['provice_id'];
        }
        if ($request['city_id']) {
            $where['city_id'] = $request['city_id'];
        }
        if ($request['area_id']) {
            $where['area_id'] = $request['area_id'];
        }
        $keyword = $request['keyword'] ? $request['keyword'] : '';
        if ($keyword) {
            if (is_numeric($keyword)) {
                $where['mobile'] = $keyword;
            } else {
                $where['name'] = ['like', '%' . $keyword . '%'];
            }
        }
        $order['id'] = 'desc';
        $rows = $agent->getList($where, '*', $order, 10);
        if ($rows) {
            $rows = $rows->toArray();
            $rows['pageNoList'] = getPageNoList($rows['last_page'], request('page', 1), 10);
        }
        return $rows;
    }

    public function editBrandInfo($request)
    {
        $brand_name = trim($request['title']);
        $name = trim($request['name']);
        $tel = trim($request['mobile']);
        $address = trim($request['address']);
        if (empty($brand_name) || empty($name) || empty($tel) || empty($address)) {
            $res = ['status' => 0, 'msg' => "信息不能为空"];
            return $res;
        }
        // 验证手机格式
        $telReg = "/^1[3|4|5|7|8][0-9]{9}$/";
        if (!preg_match($telReg, $tel, $arr)) {
            $res = ['status' => 0, 'msg' => "手机号格式不正确"];
            return $res;
        }

        $insertdata['name'] = $name;
        $insertdata['title'] = $brand_name;
        $insertdata['mobile'] = $tel;
        $insertdata['address'] = $address;
        $insertdata['updated_at'] = date("Y-m-d H:i:s", time());
        $condition['id'] = $request['id'];
        $aid = $this->up($condition, $insertdata);
        if (!$aid) {
            $res = ['status' => 0, 'msg' => "修改品牌商失败"];
            return $res;
        }
        if ($request['pics']) {
            $imgPath = upImgs($request['pics'], 'lisence/');
            $data['pic'] = $imgPath;
        }
        $res = ['status' => 1, 'msg' => "修改品牌商成功"];
        return $res;
    }

    public function getBrandList($request)
    {
        $keyword = $request['keyword'] ? $request['keyword'] : '';
        $where = [];
        if ($keyword) {
            if (is_numeric($keyword)) {
                $where['mobile'] = $keyword;
            } else {
                $where['title'] = ['like', '%' . $keyword . '%'];
            }
        }

        $start = date("Y-m-d", strtotime($request['starttime']));
        $end = date("Y-m-d", strtotime($request['endtime']));
        $start1 = $start;
        $end1 = $end;
        if ($start > $end) {
            $start1 = $end;
            $end1 = $start;
        }
        if ($request['starttime'] && $request['endtime']) {
            $where['created_at'] = ['glt', [['>', $start1], ['<=', $end1]]];;
        }

        $order['id'] = 'desc';
        $rows = $this->getList($where, '*', $order, 10);
        if ($rows) {
            $rows = $rows->toArray();
            $rows['pageNoList'] = getPageNoList($rows['last_page'], request('page', 1), 10);
        }
        return $rows;
    }

    public function getApplyList($request)
    {
        $where = [];
        if ($request['status']) {
            $where['status'] = ['in', [1, 2]];
        } else {
            $where['status'] = 0;
        }

        $keyword = $request['keyword'] ? $request['keyword'] : '';
        if ($keyword) {
            if (is_numeric($keyword)) {
                $where['mobile'] = $keyword;
            } else {
                $where['name'] = ['like', '%' . $keyword . '%'];
            }
        }

        $start = date("Y-m-d", strtotime($request['starttime']));
        $end = date("Y-m-d", strtotime($request['endtime']));
        $start1 = $start;
        $end1 = $end;
        if ($start > $end) {
            $start1 = $end;
            $end1 = $start;
        }
        if ($request['starttime'] && $request['endtime']) {
            $where['created_at'] = ['glt', [['>', $start1], ['<=', $end1]]];;
        }

        $order['id'] = 'desc';
        $rows = $this->getList($where, '*', $order, 10);
        if ($rows) {
            $rows = $rows->toArray();
            $rows['pageNoList'] = getPageNoList($rows['last_page'], request('page', 1), 10);
        }
        return $rows;
    }

    /**
     * 添加品牌
     * @param $request
     * @return array
     */
    public function addBrand($request)
    {

        $tel = trim($request['mobile']);     //手机号就是用户名
        $password = trim($request['password']);   //密码
        $cpassword = trim($request['cpassword']);  //确认密码
        $brand_name = trim($request['brand_name']); //品牌名称
        $name = trim($request['name']);            //负责人
        $username = $tel;
        $address = trim($request['address']);      //地址
        if (!$tel || !$password || !$brand_name || !$name || !$address || !$cpassword) {
            $res = ['status' => 0, 'msg' => "请填写完整所有注册信息"];
            return $res;
        }

        if ($password != $cpassword) {
            $res = ['status' => 0, 'msg' => "两次密码输入不一致"];
            return $res;
        }

        // 验证手机格式
        $telReg = "/^1[3|4|5|7|8][0-9]{9}$/";
        if (!preg_match($telReg, $tel, $arr)) {
            $res = ['status' => 0, 'msg' => "手机号格式不正确"];
            return $res;
        }

        $insertdata['username'] = $username;
        $insertdata['password'] = md5($password);
        $insertdata['name'] = $name;
        $insertdata['title'] = $brand_name;
        $insertdata['mobile'] = $tel;
        $insertdata['address'] = $address;
        $insertdata['status'] = 0;
        $insertdata['created_at'] = date("Y-m-d H:i:s", time());
        $insertdata['updated_at'] = date("Y-m-d H:i:s", time());


        //判断用户和品牌是否存在
        $res = $this->getOne(array('username' => $username));

        if ($res) {
            $res = ['status' => 0, 'msg' => "用户名已存在,无法添加"];
            return $res;
        }

        //代理名
        $res = $this->getOne(array('title' => $brand_name));
        //dd($res);
        if ($res) {
            $res = ['status' => 0, 'msg' => "该品牌已存在,无法添加"];
            return $res;
        }
        if (empty($request['img'])) {
            $res = ['status' => 0, 'msg' => "请上传代理书"];
            return $res;
        }
        $imgPath = upImgs($request['img'], 'lisence');
        $insertdata['license'] = $imgPath;
        if (empty($imgPath)) {
            $res = ['status' => 0, 'msg' => "代理书上传失败"];
            return $res;
        }


        $aid = $this->add($insertdata);
        if (!$aid) {
            $res = ['status' => 0, 'msg' => "注册品牌代理商失败"];
            return $res;
        }
//        $SALT = "whydyyeeyryereu**((((541";
//        // 生成token
//        $token['token'] = md5($SALT . $aid);
//        $token['admin'] = $aid;
//        session('token', $token);
        $res = ['status' => 1, 'msg' => "注册品牌代理成功，请耐心等待审核"];
        $info = $this->getOne(array('username' => $tel));
        session(["adminname" => $info['username']]);
        session(['adminId' => $info['id']]);
        return $res;
    }


    public function verify($request)
    {

        $where['id'] = $request['id'];
        $res = $this->up($where, ['status' => $request['status']]);
        $ajaxData['status'] = $res ? 1 : 0;
        $ajaxData['msg'] = '操作成功！';
        if (!$res) {
            $ajaxData['msg'] = '操作失败！';
        }
        return $ajaxData;
    }


    //获取品牌代理书
    public function getImageData()
    {
        return $this->getOne(array('id' => session('adminId')), 'proxy');
    }


    //ajax删除品牌
    public function deleteOneBrand($request)
    {

        //dd($request['id']);

        $where['id'] = $request['id'];


        $res = $this->del($where);
        if (!$res) {
            $data['status'] = 0;
            $data['msg'] = '删除品牌商失败！';
            return $data;
        }

        $data['status'] = 1;
        $data['msg'] = '删除品牌商成功！';
        return $data;

    }

    public function modifyPwd($request)
    {
        $where['id'] = session('adminId');
        $brand = $this->getOne($where);
        if ($brand['password'] != md5($request['oldpwd'])) {
            return '原始密码错误！';
        }
        if ($request['pwd'] && $request['repwd']) {
            if ($request['pwd'] != $request['repwd']) {
                return '两次密码不一致！';
            }
        }
        $data['password'] = md5($request['pwd']);
        $res = $this->up($where, $data);
        if (!$res) {
            return '修改失败！';
        }
        return '修改成功！';
    }


}